package org.msfj.common.util.jwt;

import org.msfj.common.annotation.Constants;
import org.msfj.common.util.RsaKeyHelper;
import org.msfj.common.util.StringHelper;
import cn.hutool.core.date.DateUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

/**
 * Created by ace on 2017/9/10.
 */
public class JWTHelper {
    private static RsaKeyHelper rsaKeyHelper = new RsaKeyHelper();
    /**
     * 密钥加密token
     *
     * @param jwtInfo
     * @param priKeyPath
     * @param expire
     * @return
     * @throws Exception
     */
    public static String generateToken(IJWTInfo jwtInfo, String priKeyPath, int expire) throws Exception {
        String compactJws = Jwts.builder()
                .setSubject(jwtInfo.getUniqueName())
                .claim(Constants.JWT_KEY_USER_ID, jwtInfo.getId())
                .claim(Constants.JWT_KEY_NAME, jwtInfo.getName())
                .setExpiration(DateUtil.offsetSecond(new Date(),expire))
                .signWith(SignatureAlgorithm.RS256, rsaKeyHelper.getPrivateKey(priKeyPath))
                .compact();
        return compactJws;
    }

    /**
     * 公钥解析token
     *
     * @param token
     * @return
     * @throws Exception
     */
    public static Jws<Claims> parserToken(String token, String pubKeyPath) throws Exception {
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(rsaKeyHelper.getPublicKey(pubKeyPath)).parseClaimsJws(token);
        return claimsJws;
    }

    /**
     * 获取token中的用户信息
     *
     * @param token
     * @param pubKeyPath
     * @return
     * @throws Exception
     */
    public static IJWTInfo getInfoFromToken(String token, String pubKeyPath) throws Exception {
        Jws<Claims> claimsJws = parserToken(token, pubKeyPath);
        Claims body = claimsJws.getBody();
        long buffer = (body.getExpiration().getTime() - System.currentTimeMillis()) / 1000;
        JWTInfo jwtInfo = new JWTInfo(body.getSubject(), StringHelper.getObjectValue(body.get(Constants.JWT_KEY_USER_ID)), StringHelper.getObjectValue(body.get(Constants.JWT_KEY_NAME)));
        jwtInfo.setBuffer(buffer);
        return jwtInfo;
    }

}
